package com.woniu.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.sun.istack.internal.NotNull;
import com.woniu.entity.EverEmp;
import com.woniu.entity.EverSalary;
import com.woniu.log.AnnotationLog;
import com.woniu.service.IEverSalaryService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lkl
 * @since 2020-11-29
 */
@RestController
@RequestMapping("/ever-salary")
@CrossOrigin  //跨域
public class EverSalaryController {
    @Autowired
    private IEverSalaryService salaryService;

    /**
     * 我的工作台
     * 根据eid查询
     * 分页
     * @param eid
     * @param current
     * @param size
     * @return
     */
    @AnnotationLog(descrption = "资金:展示员工的工资")
    @GetMapping("findByEid/{eid}/{current}/{size}")
    public Page<EverSalary> findByEid(@NotNull @PathVariable Integer eid,
                                      @PathVariable Integer current,
                                      @PathVariable Integer size ){
        Page<EverSalary> everSalaries = salaryService.findByEid(eid, size, current);
        return everSalaries;
    }
    /**
     * 查询所有用户
     */
    @AnnotationLog(descrption = "资金:展示员工的工资")
    @PostMapping("findAll")
//    数据缓存到redis中
//    @Cacheable(value = "index",key = "'findAll'")
    public List<EverSalary> findAll(
            String ename,
            Integer current,
            Integer size,
            Date starttime,
            Date endtime,
            String salstate
    ) {
        List<EverSalary> salaryList = salaryService.findAll(ename, current, size, starttime, endtime, salstate);
        return salaryList;
    }

    /**
     * 查询一条工资信息
     * @param sid
     * @return
     */
    @AnnotationLog(descrption = "资金:查询一条工资详情")
    @GetMapping("findOne")
    public EverSalary findOne(Integer sid){
        return salaryService.findOne(sid);
    }

    /**
     * 修改一条工资的状态 (财务对工资进行确认)
     * @param salary
     * @return
     */


    @PutMapping("updateOne")
    public Integer updateOne(@RequestBody EverSalary salary){
        System.out.println(salary.getSid());
        return salaryService.updateOne(salary);
    }

    /**
     * 修改多条工资的状态  (财务对工资进行确认)
     * @param
     * @return
     */
    @AnnotationLog(descrption = "资金:修改多条工资信息")
    @PutMapping("updateMany")
    public Integer updateMany(Long[] sids){
        return salaryService.updateMany(sids);
    }

    /**
     * 自动生成个人工资流水
     */
    @AnnotationLog(descrption = "资金:自动生成上月的工资报表")
    @GetMapping("genSalary")
    public void genSalary() throws ParseException {
        salaryService.genSalary();
    }

    /**
     * 修改员工的基本工资
     */
    @AnnotationLog(descrption = "资金:修改一个员工的基本工资")
    @PostMapping("changeSalary")
    public Integer changeSalary(@RequestBody EverEmp emp){
        return salaryService.changeSalary(emp);
    }

    /**
     * 更改工资状态为 未审核
     * @param sid
     * @return
     */
    @AnnotationLog(descrption = "资金:修改一个员工的工资审核")
    @GetMapping("returnSalary")
    public Integer returnSalary(Long sid){
        return salaryService.returnSalary(sid);
    }

    /**
     * 导出工资
     * @return
     */
    @AnnotationLog(descrption = "资金:导出员工的工资表")
    @PostMapping("getsalary")
    public ResponseEntity<byte[]> getsalary(
                            String ename,
                            Date starttime,
                            Date endtime,
                            String salstate
    ) throws IOException {
        //获取所有的工资
        List<EverSalary> salaryList = salaryService.getsalary(ename,starttime,endtime,salstate);
        // 获取linux服务器的项目根路径
        String path2 = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent();
        // filePath为：file:/usr/local/zyd
        path2=path2.substring(5, path2.length());

        //本地路径
        String path = "C:\\excel\\upload";
        File file1=new File(path2);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //已时间作为文件名一部分
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        //获取开始时间的下一个月
        Calendar nestMonthFirstDateCal = Calendar.getInstance();
        nestMonthFirstDateCal.setTime(starttime);
        nestMonthFirstDateCal.add(Calendar.MONTH,+1);
        nestMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
        Date lastMonthFirsttime = nestMonthFirstDateCal.getTime();
//        endtime.
        String end = simpleDateFormat.format(endtime);
        String start = simpleDateFormat.format(lastMonthFirsttime);
        //默认打印所有
        String time = "全部";
        if(!start.equals("1900-01") && (end.equals("2200-01"))){
            time = start;
        }
        else if((!start.equals("1900-01")) && (!end.equals("2200-01")) ){
            time = start +"至"+ end;
        }
        else if((start.equals("1900-01")) && (!end.equals("2200-01"))){
            time = end;
        }
        if((!start.equals("1900-01")) && (!end.equals("2200-01")) && start.equals(end)){
            time = start;
        }
        // 也可修改为 xls ,注实际中表名 写死值去覆盖，避免服务器数据冗余
        String filename = "员工工资表.xls";
        // 存储File
        File tfile = new File(path + "\\" + filename);
        // 目录
        File mfile = new File(path);
        if (!tfile.exists()) {
            mfile.mkdir();
        }
        // 生成excel
        XSSFWorkbook workbook = new XSSFWorkbook();
        //设置表内的小表名
        XSSFSheet sheet = workbook.createSheet(time);
        int rownum = 0;
        XSSFRow row1 = sheet.createRow(rownum);
        row1.createCell(0).setCellValue("日期");
        row1.createCell(1).setCellValue("姓名");
        row1.createCell(2).setCellValue("基础工资");
        row1.createCell(3).setCellValue("业务工资");
        row1.createCell(4).setCellValue("总工资");
        row1.createCell(5).setCellValue("状态");
        rownum =1;   //循环给每一行赋值
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        for (EverSalary salary : salaryList) {
            XSSFRow row = sheet.createRow(rownum);
            row.createCell(0).setCellValue(simpleDateFormat2.format(salary.getSaltime()));
            row.createCell(1).setCellValue(salary.getEmp().getEname());
            row.createCell(2).setCellValue(salary.getSal());
            row.createCell(3).setCellValue(salary.getCommission()+"");
            //计算总工资
            String sum = Double.valueOf(salary.getSal()) + salary.getCommission().doubleValue() + "";
            row.createCell(4).setCellValue(sum);
            if(salary.getSalstate().equals("1")){
                row.createCell(5).setCellValue("未审核");
            }else {
                row.createCell(5).setCellValue("已审核");
            }
            rownum++;
        }
        // 数据保存到workbook
        try {
            workbook.write(new FileOutputStream(tfile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建请求头对象
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment(下载方式)打开
        headers.setContentDispositionFormData("attachment", downloadFileName);
        // application/octet-stream:二进制流数据（最常见的文件下载）
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //将服务器上的数据返给前端去下载
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(tfile),
                headers, HttpStatus.CREATED);
        return responseEntity;
    }


}

